package com.zyp.jobseeker.controller;

import com.zyp.jobseeker.entity.Interview;
import com.zyp.jobseeker.enums.UserRole;
import com.zyp.jobseeker.service.InterviewService;
import com.zyp.jobseeker.utils.ResultUtil;
import com.zyp.jobseeker.utils.JwtUtil;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 面试邀请控制器
 */
@RestController
@RequestMapping("/api/interviews")
@PreAuthorize("hasAuthority('STUDENT') or hasAuthority('ENTERPRISE')")
public class InterviewController {

    private static final Logger logger = LoggerFactory.getLogger(InterviewController.class);

    @Autowired
    private InterviewService interviewService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 企业主动邀请学生面试
     */
    @PostMapping
    public ResultUtil<Map<String, Object>> createInterviewInvitation(
            @RequestHeader("Authorization") String token,
            @RequestBody Interview interview) {
        try {
            logger.info("[面试邀请] 收到企业主动邀请请求，参数: {}", interview);
            
            // 从请求头中获取token
            if (token == null || !token.startsWith("Bearer ")) {
                return ResultUtil.fail(401, "未提供有效的认证信息");
            }
            token = token.substring(7);
            
            // 验证token有效性
            if (!jwtUtil.isValidJwtFormat(token)) {
                logger.warn("[面试邀请] ❌ 无效的JWT格式");
                return ResultUtil.fail(401, "无效的JWT格式");
            }

            if (jwtUtil.isTokenExpired(token)) {
                logger.warn("[面试邀请] ❌ Token已过期");
                return ResultUtil.fail(401, "Token已过期");
            }

            // 获取用户信息
            Long enterpriseId = jwtUtil.getUserIdFromToken(token);
            Integer role = jwtUtil.getRoleFromToken(token);

            // 权限验证
            if (role != null && role != UserRole.ENTERPRISE.getCode()) {
                logger.warn("[面试邀请] ❌ 权限不足: 非企业角色");
                return ResultUtil.fail(403, "仅企业可主动邀请面试");
            }

            // 验证必填参数
            if (interview.getStudentId() == null) {
                logger.warn("[面试邀请] ❌ 未提供学生ID");
                return ResultUtil.fail(400, "请提供学生ID");
            }
            if (interview.getPositionId() == null) {
                logger.warn("[面试邀请] ❌ 未提供岗位ID");
                return ResultUtil.fail(400, "请提供岗位ID");
            }
            if (interview.getInterviewTime() == null) {
                logger.warn("[面试邀请] ❌ 未提供面试时间");
                return ResultUtil.fail(400, "请提供面试时间");
            }
            if (interview.getInterviewLocation() == null || interview.getInterviewLocation().trim().isEmpty()) {
                logger.warn("[面试邀请] ❌ 未提供面试地点");
                return ResultUtil.fail(400, "请提供面试地点");
            }

            // 设置企业ID
            interview.setEnterpriseId(enterpriseId);

            // 调用服务层
            Map<String, Object> result = interviewService.createInterviewInvitation(interview);
            
            if (result.containsKey("code") && (Integer) result.get("code") == 500) {
                logger.warn("[面试邀请] ❌ 创建失败: {}", result.get("message"));
                return ResultUtil.fail(500, (String) result.get("message"));
            }

            logger.info("[面试邀请] ✅ 企业主动邀请成功，面试ID: {}", result.get("id"));
            return ResultUtil.success("面试邀请已发送", result);

        } catch (Exception e) {
            logger.error("[面试邀请] ❌ 创建失败", e);
            return ResultUtil.fail(500, "创建面试邀请失败: " + e.getMessage());
        }
    }

    /**
     * 学生查看收到的面试邀请
     */
    @GetMapping("/student")
    public ResultUtil<PageInfo<Map<String, Object>>> getInterviewsByStudent(
            @RequestHeader("Authorization") String token,
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            logger.info("[面试邀请] 收到学生面试邀请查询请求，参数: status={}, page={}, size={}", status, page, size);
            
            // 从请求头中获取token
            if (token == null || !token.startsWith("Bearer ")) {
                return ResultUtil.fail(401, "未提供有效的认证信息");
            }
            token = token.substring(7);
            
            // 验证token
            if (!jwtUtil.isValidJwtFormat(token) || jwtUtil.isTokenExpired(token)) {
                logger.warn("[面试邀请] ❌ Token验证失败");
                return ResultUtil.fail(401, "无效Token");
            }

            // 获取用户信息
            Long studentId = jwtUtil.getUserIdFromToken(token);
            Integer role = jwtUtil.getRoleFromToken(token);

            // 权限验证
            if (role != null && role != UserRole.STUDENT.getCode()) {
                logger.warn("[面试邀请] ❌ 非学生用户尝试查询学生面试邀请");
                return ResultUtil.fail(403, "仅学生可查看收到的面试邀请");
            }

            // 调用服务层
            PageInfo<Map<String, Object>> interviews = interviewService.getInterviewsByStudent(
                    studentId, status, page, size);

            logger.info("[面试邀请] ✅ 学生面试邀请查询完成，返回结果数: {}", interviews.getTotal());
            return ResultUtil.success("查询成功", interviews);

        } catch (Exception e) {
            logger.error("[面试邀请] ❌ 查询失败", e);
            return ResultUtil.fail(500, "查询面试邀请失败: " + e.getMessage());
        }
    }

    /**
     * 企业查看发出的面试邀请
     */
    @GetMapping("/enterprise")
    public ResultUtil<PageInfo<Map<String, Object>>> getInterviewsByEnterprise(
            @RequestHeader("Authorization") String token,
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            logger.info("[面试邀请] 收到企业面试邀请查询请求，参数: status={}, page={}, size={}", status, page, size);
            
            // 从请求头中获取token
            if (token == null || !token.startsWith("Bearer ")) {
                return ResultUtil.fail(401, "未提供有效的认证信息");
            }
            token = token.substring(7);
            
            // 验证token
            if (!jwtUtil.isValidJwtFormat(token) || jwtUtil.isTokenExpired(token)) {
                logger.warn("[面试邀请] ❌ Token验证失败");
                return ResultUtil.fail(401, "无效Token");
            }

            // 获取用户信息
            Long enterpriseId = jwtUtil.getUserIdFromToken(token);
            Integer role = jwtUtil.getRoleFromToken(token);

            // 权限验证
            if (role != null && role != UserRole.ENTERPRISE.getCode()) {
                logger.warn("[面试邀请] ❌ 非企业用户尝试查询企业面试邀请");
                return ResultUtil.fail(403, "仅企业可查看发出的面试邀请");
            }

            // 调用服务层
            PageInfo<Map<String, Object>> interviews = interviewService.getInterviewsByEnterprise(
                    enterpriseId, status, page, size);

            logger.info("[面试邀请] ✅ 企业面试邀请查询完成，返回结果数: {}", interviews.getTotal());
            return ResultUtil.success("查询成功", interviews);

        } catch (Exception e) {
            logger.error("[面试邀请] ❌ 查询失败", e);
            return ResultUtil.fail(500, "查询面试邀请失败: " + e.getMessage());
        }
    }

    /**
     * 学生接受面试邀请
     */
    @PutMapping("/{id}/accept")
    public ResultUtil<Map<String, Object>> acceptInterview(
            @RequestHeader("Authorization") String token,
            @PathVariable Long id) {
        try {
            logger.info("[面试邀请] 收到学生接受邀请请求，面试ID: {}", id);
            
            // 从请求头中获取token
            if (token == null || !token.startsWith("Bearer ")) {
                return ResultUtil.fail(401, "未提供有效的认证信息");
            }
            token = token.substring(7);
            
            // 验证token
            if (!jwtUtil.isValidJwtFormat(token) || jwtUtil.isTokenExpired(token)) {
                logger.warn("[面试邀请] ❌ Token验证失败");
                return ResultUtil.fail(401, "无效Token");
            }

            // 获取用户信息
            Long studentId = jwtUtil.getUserIdFromToken(token);
            Integer role = jwtUtil.getRoleFromToken(token);

            // 权限验证
            if (role != null && role != UserRole.STUDENT.getCode()) {
                logger.warn("[面试邀请] ❌ 非学生用户尝试接受面试邀请");
                return ResultUtil.fail(403, "仅学生可接受面试邀请");
            }

            // 调用服务层
            Map<String, Object> result = interviewService.acceptInterview(id, studentId);
            
            if (result.containsKey("code") && (Integer) result.get("code") == 500) {
                logger.warn("[面试邀请] ❌ 接受失败: {}", result.get("message"));
                return ResultUtil.fail(500, (String) result.get("message"));
            }

            logger.info("[面试邀请] ✅ 学生接受面试邀请成功，面试ID: {}", id);
            return ResultUtil.success("已接受面试邀请", result);

        } catch (Exception e) {
            logger.error("[面试邀请] ❌ 接受失败", e);
            return ResultUtil.fail(500, "接受面试邀请失败: " + e.getMessage());
        }
    }

    /**
     * 学生拒绝面试邀请
     */
    @PutMapping("/{id}/reject")
    public ResultUtil<Map<String, Object>> rejectInterview(
            @RequestHeader("Authorization") String token,
            @PathVariable Long id) {
        try {
            logger.info("[面试邀请] 收到学生拒绝邀请请求，面试ID: {}", id);
            
            // 从请求头中获取token
            if (token == null || !token.startsWith("Bearer ")) {
                return ResultUtil.fail(401, "未提供有效的认证信息");
            }
            token = token.substring(7);
            
            // 验证token
            if (!jwtUtil.isValidJwtFormat(token) || jwtUtil.isTokenExpired(token)) {
                logger.warn("[面试邀请] ❌ Token验证失败");
                return ResultUtil.fail(401, "无效Token");
            }

            // 获取用户信息
            Long studentId = jwtUtil.getUserIdFromToken(token);
            Integer role = jwtUtil.getRoleFromToken(token);

            // 权限验证
            if (role != null && role != UserRole.STUDENT.getCode()) {
                logger.warn("[面试邀请] ❌ 非学生用户尝试拒绝面试邀请");
                return ResultUtil.fail(403, "仅学生可拒绝面试邀请");
            }

            // 调用服务层
            Map<String, Object> result = interviewService.rejectInterview(id, studentId);
            
            if (result.containsKey("code") && (Integer) result.get("code") == 500) {
                logger.warn("[面试邀请] ❌ 拒绝失败: {}", result.get("message"));
                return ResultUtil.fail(500, (String) result.get("message"));
            }

            logger.info("[面试邀请] ✅ 学生拒绝面试邀请成功，面试ID: {}", id);
            return ResultUtil.success("已拒绝面试邀请", result);

        } catch (Exception e) {
            logger.error("[面试邀请] ❌ 拒绝失败", e);
            return ResultUtil.fail(500, "拒绝面试邀请失败: " + e.getMessage());
        }
    }
}
